﻿<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>

<% 
   ModelMetadata meta = ViewData.ModelMetadata;
   string propertyName = meta.PropertyName;
   string displayName = meta.DisplayName;
   string masterController = meta.AdditionalValues["MasterController"].ToString();
   string relatedProperty = meta.AdditionalValues.ContainsKey("RelatedProperty") ? meta.AdditionalValues["RelatedProperty"].ToString() : "";
   
   ViewDataDictionary VDD = new ViewDataDictionary();
   VDD["EntityName"] = meta.ContainerType.Name;
   VDD["FieldName"] = propertyName;
   VDD["Mode"] = "Edit";

   if (Model != null)
   {
       string[] cascadingChain = meta.AdditionalValues["CascadingChain"].ToString().Split('$');

       for (int i = cascadingChain.Length - 1; i >=0; i--)
       {
           string[] items = cascadingChain[i].Split('!');
           //string tableName = items[1];
           string chainPropertyName = items[2];
           bool isFirstItem = i == (cascadingChain.Length - 1);
           bool isLastItem = i == 0;

           if (isFirstItem)
           {
               VDD[chainPropertyName] = Model;
           }
           else
           {
               string[] parentItems = cascadingChain[i + 1].Split('!');
               string parentTableName = parentItems[1];
               string parentPropertyName = parentItems[2];
               if (VDD[parentPropertyName] != null)
               {
                   int parentID = (int)VDD[parentPropertyName];
                   VDD[chainPropertyName] = Smartec.Accounts.Camel.AMS.Model.Facades.AMSManagerFacade.GetFieldValue(parentTableName, chainPropertyName, parentID);
               }
           }
       }
   }

   StringBuilder ajaxRequestData = new StringBuilder("PartialView!CascadingField");
   foreach (KeyValuePair<string, object> kv in VDD)
   {
       ajaxRequestData.Append(string.Format("${0}!{1}", kv.Key, kv.Value == null ? "" : kv.Value.ToString()));
   }
   ajaxRequestData.Append("$p!");
   string ajaxRequestParameters = ajaxRequestData.ToString();

   string iframeSrc = string.Format("http://{0}/{1}/Create?iframe=true", Request.Url.Authority, masterController);
   string iframeInitSrc = string.Format("http://{0}/{1}/RenderEmptyView", Request.Url.Authority, "Home");
%>

<table class="cascadingfieldtable">
<tr>
<td>
<div id="partial<%:propertyName %>">
<% Html.RenderPartial("~/Views/Shared/CascadingField.ascx", VDD);%>
</div>
</td>
<td><img id="loading<%:propertyName %>" src="../../../Content/Default/loading.gif" alt="Updating ..." style="display: none;float:right;margin-left:5px;margin-right:5px;" /></td>
<td><a id="feedback-open-button<%:propertyName %>" href="#" style="white-space:nowrap;">Create New <%:displayName%></a></td>
</tr>
</table>

     <% Html.Telerik().Window()
           .Name("Window" + propertyName)
           .ClientEvents(
              events =>
                events.OnClose("onClose" + propertyName).OnLoad((AMSManager.InsideIframe ? "onLoad" : "onLoad2") + propertyName)
                )
           .Title("Create New " + displayName)
           .Draggable(true)
           .Resizable()
           .Scrollable(false)
           .Modal(true)
           .Buttons(b => b.Maximize().Close())
           //.LoadContentFrom("Create","Countries")
           .LoadContentFrom(iframeInitSrc)
           .Width(900)
           .Height(500)
           .Visible(false)
           .Render();
    %>
    
 <% Html.Telerik().ScriptRegistrar()
           .OnDocumentReady(() =>
           {%>
               // open the initially hidden window when the button is clicked
               $('#feedback-open-button<%:propertyName %>')
                    .click(function(e) {
                        e.preventDefault();
                         var window = $("#Window<%:propertyName %>").data("tWindow");
                         var iframe = $("#Window<%:propertyName %> iframe")[0];
                         iframe.src = "<%:iframeSrc%>";
                        window.center().open();
                    });
               // add button hovers
               $('.t-button').live('mouseenter', $.telerik.buttonHover)
                             .live('mouseleave', $.telerik.buttonLeave);

                            <%-- if('<%:isAjax%>'=='True')
                             {
               RenderForiegnFieldData<%:propertyName %>()
               }--%>
           <%}); %>

                <a id="closeWindow<%:propertyName %>" href="#" onclick="closeWindow<%:propertyName %>();"  style="visibility:hidden">close</a>
                <a id="reloadForiegnFieldData<%:propertyName %>" href="#" onclick="reloadForiegnFieldData<%:propertyName %>();"  style="visibility:hidden">reload</a>

  <%--  <script type='text/javascript'>
        function onCloseCategoryPopup(e) {
            var iframe = $("#CategoryPopup iframe")[0];
            iframe.src = "<%:categoryPopupEmptyUrl%>"; //+ currentTabIndex + "$" 
        }
        function closeCategoryPopup() {
            var window = $("#CategoryPopup").data("tWindow");
            window.close();
        }

        function reloadParentWindow() {
            window.location.href = "<%:categoryPopupUrl%>" + "index/" + currentTabIndex + (insideIfram == true ? "?iframe=true" : "");
        }

        </script>--%>
        
             <script type="text/javascript">
             
             function RenderForiegnFieldData<%:propertyName %>() {
                     $('#loading<%:propertyName %>').show();
                     $('#partial<%:propertyName %>').html('');
                     $('#partial<%:propertyName %>').load('/Home/RenderCascadingField/<%:ajaxRequestParameters %>'+((typeof <%:propertyName %>AjaxParameter == 'undefined')?'':<%:propertyName %>AjaxParameter), function (html) {
                         $('#partial<%:propertyName %>')[0].value = html;
                         $('#loading<%:propertyName %>').hide();
                         if('<%:relatedProperty %>'.length>0)
                         {
                            $('#reloadForiegnFieldData<%:relatedProperty %>', parent.document).click();
                         }
                                          });
                 }

                 function onLoad<%:propertyName %>(e) {
                     //                    $.ajaxSetup({ cache: false }); 
                     //alert('Window loaded');
                     maximizeWindow<%:propertyName %>();
                 }
                 function onLoad2<%:propertyName %>(e) {
                    
                 }
                 function onClose<%:propertyName %>(e) {
                     var iframe = $("#Window<%:propertyName %> iframe")[0];
                     iframe.src = "<%:iframeInitSrc%>";
                 }
                 function onOpen<%:propertyName %>(e) {
//                     alert('OnOpen');
                 }
                 function onActivate<%:propertyName %>(e) {
//                     alert('OnActivate');
                 }
                 function onRefresh<%:propertyName %>(e) {
//                     alert('OnRefresh');
                 }

                 function reloadForiegnFieldData<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.close();
                     RenderForiegnFieldData<%:propertyName %>()
                 }

                 function openWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.open();
                 }

                 function closeWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.close();
                 }

                 function refreshWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     alert("refresh");
                     window.refresh();
                 }

                 function maximizeWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.maximize();
                 }

                 function restoreWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.restore();
                 }

                 function centerWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.center();
                 }
        </script>
